package com.qiwenshare.file.websocket;

import com.qiwenshare.file.util.JsonUtils;
import com.qiwenshare.file.vo.device.DeviceInfo;
import com.qiwenshare.file.vo.device.WSDataType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.server.ServerEndpoint;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/websocket/{sid}")
@Component
public class  WebSocketServer {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
//    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    public static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<Session, DeviceInfo> devicePools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }else{

        }
    }

    //给指定用户发送信息
    public void sendInfo(String userName, String message) {
        try {
            Session session = sessionPools.get(userName);
            sendMessage(session, message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void SendAll(String message) {
        for(String key : sessionPools.keySet()){
            sendInfo(key,message);
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName) {
        if(sessionPools.containsKey(userName)){
            devicePools.remove(sessionPools.get(userName));
            sessionPools.remove(userName);
        }
        sessionPools.put(userName, session);
        devicePools.put(session,new DeviceInfo());
        //System.out.println(userName + " 加入 当前连接数为 " + sessionPools.size());
    }


    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
        if(sessionPools.containsKey(userName)){
            devicePools.remove(sessionPools.get(userName));
            sessionPools.remove(userName);
        }
        //System.out.println(userName + " 断开 当前连接数为 " + sessionPools.size());
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        WSDataType wsDataType = JsonUtils.jsonToPojo(message, WSDataType.class);
        switch (wsDataType.getMsgType()){
            case "volumn":
                try{
                    int volumn = Integer.parseInt(wsDataType.getData());
                    getDeviceInfo(session).setVolumn(volumn);
                }catch(NumberFormatException e)
                {
                    System.out.println("volumn获取"+e.getMessage());
                }
                break;
            case "brightness":
                try{
                    int brightness = Integer.parseInt(wsDataType.getData());
                    getDeviceInfo(session).setBrightness(brightness);
                }catch(NumberFormatException e)
                {
                    System.out.println("brightness获取"+e.getMessage());
                }
                break;
            case "ipv4":
                getDeviceInfo(session).setIp(wsDataType.getData());
                break;
            case "online":
                try{
                    boolean online =  Boolean.parseBoolean(wsDataType.getData());
                    getDeviceInfo(session).setOnline(online);
                }catch(NumberFormatException e)
                {
                    System.out.println("online获取"+e.getMessage());
                }
                break;
        }
        getDeviceInfo(session);

        for (Session ss : sessionPools.values()) {
            try {
                sendMessage(ss, message);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    private DeviceInfo getDeviceInfo(Session session) {
        DeviceInfo deviceInfo = devicePools.get(session);
        if(deviceInfo==null){
            deviceInfo = new DeviceInfo();
        }
        return deviceInfo;
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("Websocket发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
//        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
//        onlineNum.decrementAndGet();
    }

}
